#coding=utf-8

import urllib2

from websth.library import feedparser
from datetime import datetime, timedelta

from websth.index.models import *

class BasefeedType:
    def add(self, url, owner, name = "BasefeedType"):
        """
        Add User's feed
        抓取页面，超时或找不到都会抛出异常
        """
        feed = feed.objects.filter(owner__username__exact = owner.username, url__exact = url)
        
        if len(feed) != 0:
            return True
        
        feedtype = self.__class__.__name__
            
        feed = feed(owner = owner, name = name, url = url, type = feedtype)
        
        result = urllib2.urlopen(feed.url)

        feed_parsed = feedparser.parse(result.read())
        
        feed.version = feed_parsed.version
        
        feed.updateDateStr = feed_parsed.feed.updated
        
        feed.save()
    
        for item in feed_parsed.entries:
            Item(feed = feed, title = item.title, url = item.link, description = item.description, pubishDate = datetime(*item.updated_parsed[0:6])).save()
        
        return True
    
    def update(self, feed, feed_parsed):

        #判断feed是否更新
        #由于update_parsed解析有点问题，直接判断上次数据库里保存的时间字符
        #和这一次请求是否匹配，否则说明有更新
        if feed.updateDateStr == feed_parsed.feed.updated:
            return True

        for item in feed_parsed.entries:
            i = Item.objects.filter(feed__url__exact = feed.url, publishDate__exact = datetime(*item.updated_parsed[0:6]))
            
            if (i.count() > 0):# or (feed.updateDate.utctimetuple() >= item.updated_parsed): #如果存在此item或没有更新
                break
            
            Item(feed = feed, title = item.title, url = item.link, description = item.description, publishDate = datetime(*item.updated_parsed[0:6])).save()
    
        #更新feed状态
        feed.version = feed_parsed.version
        feed.updateDateStr = feed_parsed.feed.updated
        feed.save() # update the lastupdateDate to now
        
        return True
        
    def delete(self, feed):
        for item in feed.item_set.all():
            item.delete()
        feed.delete()
        return True
    
    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s put in %s on %s:<br /><div id=\"title\"><a href=\"%s\">%s</a></div><br />%s</li>" % (item.owner.username, item.feed.name, item.publishDate, item.url, item.title, item.description)

class Douban(BasefeedType):
    def add(self, url, owner, name = "BasefeedType"):
        feed = feed.objects.filter(owner__username__exact = owner.username, url__exact = url)
        
        if len(feed) != 0:
            return True
        
        feedtype = self.__class__.__name__
            
        feed = feed(owner = owner, name = name, url = url, type = feedtype)
        
        result = urllib2.urlopen(feed.url)

        feed_parsed = feedparser.parse(result.read())
        
        feed.version = feed_parsed.version
        feed.updateDateStr = feed_parsed.feed.updated
        feed.updateDate = datetime.strptime(feed_parsed.feed.updated, '%a, %d %b %Y %H:%M:%S %Z')
        feed.save()
    
        for item in feed_parsed.entries:
            Item(feed = feed, title = item.title, url = item.link, description = item.description, pubishDate = datetime.strptime(item.updated, '%a, %d-%b-%Y %H:%M:%S %Z')).save()
        
        return True

    
    def update(self, feed, feed_parsed):

        #判断feed是否更新
        if feed.updateDateStr == feed_parsed.feed.updated:
            return True

        for item in feed_parsed.entries:
            i = Item.objects.filter(feed__url__exact = feed.url, publishDate__exact = datetime.strptime(item.updated, '%a, %d %b %Y %H:%M:%S %Z'))
            
            if (i.count() > 0):# or (feed.updateDate.utctimetuple() >= item.updated_parsed): #如果存在此item或没有更新
                break
            
            Item(feed = feed, title = item.title, url = item.link, description = item.description, publishDate = datetime.strptime(item.updated, '%a, %d %b %Y %H:%M:%S %Z')).save()
    
        #更新feed状态
        feed.version = feed_parsed.version
        feed.updateDateStr = feed_parsed.feed.updated
        feed.updateDate = datetime.strptime(feed_parsed.feed.updated, '%a, %d %b %Y %H:%M:%S %Z')
        feed.save() # update the lastupdateDate to now
        
        return True

class Fanfou(BasefeedType):
    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s says in %s on %s:<br /><id=\"title\"><a href=\"%s\">%s</a></div></li>" % (item.owner.username(), item.feed.name, item.publishDate, item.url, item.title)
    
class Blog(BasefeedType):
    #pass

    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s post in %s on %s:<br /><id=\"title\"><a href=\"%s\">%s</a></div></li>" % (item.owner.username(), item.feed.name, item.publishDate, item.url, item.title)
    
class GoogleReader(BasefeedType):
    #pass

    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s post in %s on %s:<br /><id=\"title\"><a href=\"%s\">%s</a></div></li>" % (item.owner.username(), item.feed.name, item.publishDate, item.url, item.title)
        
class Follow5(BasefeedType):
    #pass

    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s post in %s on %s:<br /><id=\"title\"><a href=\"%s\">%s</a></div></li>" % (item.owner.username(), item.feed.name, item.publishDate, item.url, item.title)
        
class Site(BasefeedType):
    #pass

    def show(self, item):
        """
        return the html of the feed's item
        @param Item item    item of this type of feed
        @return string      html code of this item
        """
        return "<li>%s post in %s on %s:<br /><id=\"title\"><a href=\"%s\">%s</a></div></li>" % (item.owner.username(), item.feed.name, item.publishDate, item.url, item.title)
        